package com.xm.task;

import com.xm.entity.UserP;
import com.xm.mapper.UserMapper;
import com.xm.util.DataSourceUtil;
import com.xm.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * mybatis-plus(逐个insert) 批量插入数据任务
 */
@Slf4j
public class MybatisPlusInsertTask implements Runnable {
    private final List<UserP> users;
    private final SqlSessionFactory sqlSessionFactory;

    public MybatisPlusInsertTask(List<UserP> users, SqlSessionFactory sqlSessionFactory) {
        this.users = users;
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public void run() {
        if(!CollectionUtils.isEmpty(users)) {
            long start = System.currentTimeMillis();
            int total = users.size();
            //批量插入users
            try (SqlSession sqlSession = this.sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                for (UserP user : users) {
                    userMapper.insert(user);
                }
                sqlSession.commit();
            } catch (Exception e) {
                log.error("MybatisPlusInsertTask 批量插入数据异常！e={}", e.getMessage());
                throw new RuntimeException(e);
            } finally {
                long time = System.currentTimeMillis() - start;
                long totalTime = DataSourceUtil.atomicLong.addAndGet(time);
                log.info("MybatisPlusInsertTask 批量插入{}条数据，耗时{}ms，totalTime={}", total, time, totalTime);
            }
        }
    }

}
